package com.iflytek.ossp.mrecharge.admin.util;

import com.csvreader.CsvWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 生成Excel的工具类
 */
@Slf4j
public class CSVUtil {

    public static File creatCsv(String path,String fileName, String[] headers, String[] mapKey, List<Map<String, Object>> list) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String filename = fileName + sdf.format(new Date()) + ".csv";
        File csvFile = new File(path + "/" + filename);
        CsvWriter csvWriter = null;
        try {
            //创建标题
            csvWriter = new CsvWriter(csvFile.getCanonicalPath(), ',', Charset.forName("GBK"));
            csvWriter.writeRecord(headers);
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //创建内容 先判断有多少行 然后每一行添加每一列的数据
            int listLength = list.size();
            int kegLeg = mapKey.length;
            for (int i = 0; i < listLength; i++) {
                Map<String, Object> map = list.get(i);
                for (int j = 0; j < kegLeg; j++) {
                     //判断VALUE为空情况
                    String str = (map.get(mapKey[j]))==null?"":map.get(mapKey[j]).toString();
                    csvWriter.write(str);
                }
                csvWriter.endRecord();
            }
            csvWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("写入CSV文件时出错! " + e.toString());
        }
        return csvFile;
    }

}
